/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} n
 * @return {ListNode}
 */
var removeNthFromEnd = function(head, n) {
  if(head.next == null && n == 1) {
    head = null;
    return head;
  }
  const headNode1 = head;
  let resultNode = head, count = n;
  while(head.next != undefined && head.next != null) {
    head = head.next;
    if(count == 0) {
      resultNode = resultNode.next;
    } else {
      count--;
    }
  }
  if(resultNode == headNode1 && count) {
    return headNode1.next;
  }
  if(resultNode.next != null)
    resultNode.next = resultNode.next.next;
  return headNode1;
};
let head = [1,2,3,4,5], n = 2;
console.log(removeNthFromEnd(head, n));
head = [1], n = 1;
console.log(removeNthFromEnd(head, n));
head = [1,2], n = 1;
console.log(removeNthFromEnd(head, n));
